package cn.hh.basic.util;

import cn.hh.user.domain.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
* 登陆上下文
* 1.当前登录人
* 2.当前登录人所拥有的角色和权限信息
* 如何在非受容器管理的类中获取受容器管理的Bean
*/
public class LoginContext {
    /*获取登陆人*/
    public static LoginInfo getLogininfo(HttpServletRequest request){
        /*获取容器对象*/
        WebApplicationContext webApplicationContext = WebApplicationContextUtils
                .getWebApplicationContext(request.getServletContext());
        /*从容器对象中拿到想要的Bean*/
        RedisTemplate redisTemplate=webApplicationContext.getBean("redisTemplate",RedisTemplate.class);
        String token = request.getHeader("token");
        Object obj = redisTemplate.opsForValue().get(token);
        if (obj!=null){
            return (LoginInfo) obj;
        }
        return null;
    }
}
